package cn.formaggie.realm;

import cn.formaggie.entity.model.roleandpermission.Permission;
import cn.formaggie.entity.model.roleandpermission.Worker;
import cn.formaggie.service.face.PermissionService;
import cn.formaggie.service.face.RoleService;
import cn.formaggie.service.face.WorkerService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public class MyRealm extends AuthorizingRealm {

    @Autowired
    private WorkerService workerService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;

    /**
     * 授予登陆的用户角色与权限名称
     * @param principal
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        String workerId= (String) principal.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
        Worker worker=workerService.getSimpleWorkerByWorkerId(workerId);
        Integer roleId=worker.getRole().getId();
        authorizationInfo.addRole(roleService.getRoleById(roleId).getRoleName());
        List<Permission> permissions=permissionService.getPermissionsByRoleId(roleId);
        List<String> stringPermissions=new ArrayList<>();
        for(Permission p:permissions){
            stringPermissions.add(p.getPermission());
        }
        authorizationInfo.addStringPermissions(stringPermissions);
        return authorizationInfo;
    }

    /**
     * 处理用户的登陆
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String workerId= (String) token.getPrincipal();

        Worker simpleWorker=workerService.getSimpleWorkerByWorkerId(workerId);
        if(simpleWorker!=null){
            SimpleAuthenticationInfo authenticationInfo=new SimpleAuthenticationInfo(simpleWorker.getWorkerId(),simpleWorker.getPassword(),"myRealm");
            return authenticationInfo;
        }
        return null;
    }
}
